﻿using System;
using SocialKit.LightRest;
using SocialKit.LightRest.OAuth;

namespace LightRestDemoSite
{
    public partial class SinaWeibo : System.Web.UI.Page
    {
        Consumer SinaConsumer
        {
            get { return (Consumer)Application["sina_consumer"]; }
        }

        AccessToken sinaAccessToken;

        protected void Page_Load(object sender, EventArgs e)
        {
            var tokenInSession = Session["sina_access_token"];

            if (tokenInSession != null)
            {
                sinaAccessToken = (AccessToken)tokenInSession;

                sinaWeiboPanel.Visible = true;
                btnLoginWithOAuth.Visible = false;
            }
        }

        protected void OnOAuthLoginClick(object sender, EventArgs e)
        {
            var requestToken = this.SinaConsumer.GetRequestToken();

            var authorizeUri = requestToken.GetNormalizedAuthorizeUri();

            Session["sina_request_token"] = requestToken;

            Response.Redirect(authorizeUri);
        }


        protected void OnUpdateClick(object sender, EventArgs e)
        {
            var form = new HttpUrlEncodedForm().Append("status", tbStatus.Text);

            var request = new OAuthHttpRequestMessage(
                "POST", "http://api.t.sina.com.cn/statuses/update.json",
                form).Sign(sinaAccessToken);

            var response = new RestClient().Send(request).ReadContentAsString();

            tbStatus.Text = "";
            tbResponse.Text = response;
        }
    }
}